package com.caration.shell;

import java.util.LinkedList;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.MessageQueue.IdleHandler;

public class ShellHandler {
	private static ShellHandler sInstance;
	private LinkedList<Runnable> mList = new LinkedList<Runnable>();
	private MessageQueue mQueue = Looper.myQueue();
	private boolean e = false;
	private String f;
	private Handler mHandler = new MyHandler();

	public static ShellHandler getInstance(){
		synchronized (sInstance) {
			if (sInstance==null) {
				sInstance=new ShellHandler();
			}
		}
		return sInstance;
	}
	
	public final void a(Runnable paramRunnable) {
		synchronized (mList) {
			mList.add(paramRunnable);
			if (mList.size() == 1)
				c();
			return;
		}
	}

	public final void a(String paramString) {
		if (!this.e) {
			new StringBuilder("pause from:").append(paramString).toString();
			this.e = true;
			this.f = paramString;
		} else {
			new StringBuilder("pause from:").append(paramString)
					.append("  error: is already pause").toString();
		}
	}

	public final void b(Runnable paramRunnable) {
		a(paramRunnable);
	}

	public final void b(String paramString) {
		if ((!this.e) || (this.f != paramString)) {
			new StringBuilder("resume from:").append(paramString)
					.append("  error: state:").append(this.e)
					.append("  current:").append(this.f).toString();
		} else {
			new StringBuilder("resume from:").append(paramString).toString();
			this.e = false;
			if (mList.size() > 0)
				c();
		}
	}

	public final boolean b() {
		return !e;
	}

	final void c() {
		if (mList.size() > 0)
//			if (!((Runnable) mList.getFirst() instanceof k))
//				mHandler.sendEmptyMessage(1);
//			else
				mQueue.addIdleHandler((IdleHandler) mHandler);
	}

	class MyHandler extends Handler implements IdleHandler {
		@Override
		public void dispatchMessage(Message msg) {

			Runnable runnable;
			synchronized (mList) {
				if (mList.size() == 0 || e)
					return;
				runnable = (Runnable) mList.removeFirst();
			}
			runnable.run();
			synchronized (mList) {
				c();
			}
		}

		@Override
		public boolean queueIdle() {
			handleMessage(null);
			return false;
		}

	}
}
